package top.someapp.applib.base;

import android.app.Activity;
import android.app.Application;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker;
import top.someapp.applib.AppContext;
import top.someapp.applib.CodeDefine;
import top.someapp.applib.kits.Nulls;

/**
 * @author zwz
 * Created on 2020-03-30
 */
public abstract class AbstractAppContext implements AppContext {

    private Activity activity;
    private PackageInfo packageInfo;

    @Override
    public boolean isDebugMode() {
        ApplicationInfo appInfo = getApplication().getApplicationInfo();
        return (0 != (appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE));
    }

    protected PackageInfo getPackageInfo() {
        if (packageInfo == null) {
            Application app = getApplication();
            PackageManager packageManager = app.getPackageManager();
            try {
                packageInfo = packageManager.getPackageInfo(app.getPackageName(), 0);
            } catch (NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return packageInfo;
    }

    @Override
    public String getAppCode() {
        String packageName = getApplication().getPackageName();
        int index = packageName.indexOf('.');
        if (index > 0) {
            packageName = packageName.substring(0, index);
        }
        return packageName;
    }

    @Override
    public String getVersionName() {
        return getPackageInfo().versionName;
    }

    @Override
    public int getVersionCode() {
        return getPackageInfo().versionCode;
    }

    @Override
    public Activity currentActivity() {
        return activity;
    }

    @Override
    public void setCurrentActivity(@NonNull Activity activity) {
        this.activity = activity;
    }

    @Override
    public boolean hasPermission(@NonNull String permission) {
        int rtn = PermissionChecker
            .checkCallingOrSelfPermission(Nulls.firstNonNull(currentActivity(), getApplication()),
                permission);
        return rtn == PermissionChecker.PERMISSION_GRANTED;
    }

    @Override
    public void requestPermission(@NonNull String[] permissions, @CodeDefine int requestCode) {
        ActivityCompat.requestPermissions(currentActivity(), permissions, requestCode);
    }

}
